import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {header} from '../data/config'
import {getUrlParam, fetch} from '../data/util'

const base = url.base,
  getDevLibList = request.getDevLibList,
  getBuildingList = request.getBuildingList,
  getHouseBuildUnit = request.getHouseBuildUnit,
  editOpenBuild = request.editOpenBuild;

const id = getUrlParam('id')

// 页面标题
const title = '开盘信息',
  action = '添加';

let form = new Vue({
  el: '#form',
  data: () => {
    return ({
      dId: '',
      dIdList: [],
      buildingId: '',
      buildingIdList: [],
      hobUnitId: '',
      hobUnitIdList: [],
      hobPeriod: '',
      hobExpectTime: '',
      // hobSpecificTime: '',
      hobPreTime: '',
      hobPreNum: '',
      hobWay: '',
      isLock: true,
      unitActive: {},
      isApp: false,
      orderFailureTime: 1,
      hobPeriodList: []
    })
  }, watch: {
    dId: function (current) {
      // this.getBuildNum(current)
    },
    buildingId: function (newV, oldV) {
      this.getHousehobPeriod(newV)
      this.getBuildNum(newV)
    },
    hobWay(current) {
      if (current == 'app-ytj') {
        this.isApp = true
      } else {
        this.isApp = false
      }
    },
  },
  mounted: function () {

    let that = this;

    let loading = layer.msg('初始化数据中...', {
      icon: 16,
      time: 0
    });

    this.initTime();

    Promise
      .all([this.getDev(), this.getBuild()])
      .then((res) => {

        layer.close(loading);

        that.isLock = false;
        that.dIdList = res[0].object;
        that.buildingIdList = res[1];

        // valid();

        setTimeout(() => {

          that.initSelect();
        }, 0)
      })
      .catch((error) => {
        // console.log(error);

        layer.close(loading);
        layer.msg(error || '初始化数据失败', {
          icon: 5
        })
      })
  },
  methods: {
    checkCount(e) {
      let val = e.target.value
      if (/^\+?[1-9][0-9]*$/.test(val) && val > 1 && val < 73) {
      } else {
        alert('请填写1-72之间的整数')
        e.target.value = ''
      }
    },
    getHousehobPeriod(res) {
      const app = this
      fetch({url: '/admin/house/getHousehobPeriod.json', data: {buildId: res}}).then(res => {
        app.hobPeriodList = res.object
      })
    },
    submitForm() {
      const app = this
      app.valid()
      $('#form').submit()
    },
    valid() {
      const _form = this

      let form_valid,
        $form = $('#form');

      $.validator.setDefaults({ // 只能放在validate规则配置之前

        // 提交事件
        submitHandler: () => {
          console.log('submit!');

          let loading_modal = layer.msg('提交中...', {
            icon: 16,
            time: 0
          });

          form.isLock = true;
          // console.log('form date:', form)
          let data
          let hobExpectTime = new Date(form.hobExpectTime)
          // let hobSpecificTime = new Date(form.hobSpecificTime)
          let str = '';
          Object.keys(form._data.unitActive).forEach(k => {
            if (str) {
              str += ',' + k
            } else {
              str = k
            }
          })
          // console.log(form)
          if (form.hobPreTime) {
            let hobPreTime = new Date(form.hobPreTime)
            data = {
              dId: form.dId,
              buildingId: form.buildingId,
              hobUnitId: str,
              hobPeriod: form.hobPeriod,
              // hobSpecificTime: Date.parse(hobSpecificTime),
              hobPreTime: Date.parse(hobPreTime),
              hobPreNum: form.hobPreNum,
              hobWay: form.hobWay,
              orderFailureTime: form.orderFailureTime || null,
              hobExpectTime: form.hobExpectTime
            }
          } else {
            data = {
              dId: form.dId,
              buildingId: form.buildingId,
              hobUnitId: str,
              hobPeriod: form.hobPeriod,
              hobExpectTime: Date.parse(hobExpectTime),
              // hobSpecificTime: Date.parse(hobSpecificTime),
              hobPreNum: form.hobPreNum,
              hobWay: form.hobWay,
              orderFailureTime: form.orderFailureTime || null,
              hobExpectTime: form.hobExpectTime
            }
          }

          // console.log('data data:', data)
          $.ajax({
            type: "POST",
            url: base + editOpenBuild,
            data: data,
            dataType: "json",
            headers: {
              myToken: Cookies.get('myToken')
            },
          })

          // $.ajax({
          //   url: base + editOpenBuild,
          //   dataType: 'JSON',
          //   type: 'POST',
          //   headers: header,
          //   contentType: 'application/json',
          //   data: data
          // })
            .done(function (res) {
              // console.log(res);

              if (res.code === -1) {
                layer.msg(res.message, {
                  icon: 5
                });

                return
              }

              layer.msg(`${action}${ title }成功`, {
                icon: 6
              });

              // 重置表单
              $.extend(form.$data, form.$options.data());

              setTimeout(() => {
                window.location = './index.html'
              }, 1000)
            })
            .fail(function (res) {
              // console.log(res);

              layer.msg(`${action}${ title }失败`, {
                icon: 5
              });

              // console.log("error");
            })
            .always(function (res) {

              layer.close(loading_modal);
              form.isLock = false

            })

        }
      });

      let validOrderFailureTime
      validOrderFailureTime = _form.isApp
      // 验证
      form_valid = $form.validate({
        errorPlacement: function (error, element) {
          error.appendTo(element.parents('.col-xs-24'))
        },
        rules: {
          orderFailureTime: {
            required: validOrderFailureTime
          },
          dId: {
            required: true
          },
          buildingId: {
            required: true
          },
          hobPeriod: {
            required: true
          },
          hobExpectTime: {
            required: true
          },
          hobPreTime: {
            required: true
          },
          hobPreNum: {
            required: true
          },
          hobWay: {
            required: true
          },
        }
      });
    },
    addTimeOut(element) {

    },
    selectUnit(e) {
      $(e.target).toggleClass('unit-active')
      let res = $(e.target).attr('data-id')
      if (this.unitActive[res]) {
        delete this.unitActive[res]
      } else {
        this.unitActive[res] = res
      }
      // console.log(this.unitActive)
    },
    test() {
      console.log(JSON.stringify(this.unitActive));
      let str = '';
      Object.keys(this.unitActive).forEach(k => {
        if (str) {
          str += ',' + k
        } else {
          str = k
        }
      })
      // console.log(str)
    },
    // 获取开发商列表
    getDev: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getDevLibList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取楼盘列表
    getBuild: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getBuildingList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res.object)
            }
            reject(res.message)
          })
          .fail(function () {
            // console.log("error")
            reject()
          })
          .always(function (res) {
          })
      })
    ),
    // 获取楼栋号
    getBuildNum: function (buildId) {
      const app = this
      let data
      id ? data = {buildId: buildId, hobUnitId: null} : data = {buildId: buildId}
      fetch({url: getHouseBuildUnit, data: data}).then(res => {
        if (res.code === 0 && res.object.length > 0) {
          app.hobUnitIdList = res.object
          console.log(app, app.hobUnitIdList)
        }
        // else {   //测试用
        //   const obj = [{idStr: 123, hbuNum: '无数栋'}, {idStr: 444, hbuNum: '无数栋2'}]
        //   // app.hobUnitIdList = res.objec;
        //   app.hobUnitIdList = obj
        //   console.log(app, app.hobUnitIdList)
        // }
      })
    },
    // 初始化快捷下拉选择框
    initSelect: function () {
      let that = this;

      $(this.$refs.select)
        .selectize({
          onChange: function (val) {
            that.dId = val;
          }
        })
    },
    // 初始化时间筛选控件
    initTime: function () {
      let that = this;

      $(this.$refs.hobExpectTime).datetimepicker({
        autoclose: true,
        todayBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        startView: 3,
        minView: 2
      })
        .on('changeDate', function (e) {
          // console.log(e.target)
          that.hobExpectTime = $(e.target).val()
          // console.log(that.hobExpectTime)
          // console.log(that)
        });

      // $(this.$refs.hobSpecificTime).datetimepicker({
      //   autoclose: true,
      //   todayBtn: true,
      //   todayHighlight: true,
      //   format: "yyyy-mm-dd hh:ii:00",
      //   startView: 4,
      //   minView: 0
      // })
      //   .on('changeDate', function (e) {
      //
      //     that.hobSpecificTime = $(e.target).val()
      //
      //   });

      $(this.$refs.hobPreTime).datetimepicker({
        autoclose: true,
        todayBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd hh:ii:00",
        startView: 4,
        minView: 0
      })
        .on('changeDate', function (e) {

          that.hobPreTime = $(e.target).val()

        });
    }
  }
});


